package com.ruicar.afs.cloud.manage.common.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.CaseStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ContractBusinessEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.manage.api.dto.OverpaymentDifferenceDTO;
import com.ruicar.afs.cloud.manage.common.entity.ManageApplyRecord;
import com.ruicar.afs.cloud.manage.common.entity.ManageOverpaymentDifference;
import com.ruicar.afs.cloud.manage.common.service.ManageApplyRecordService;
import com.ruicar.afs.cloud.manage.common.service.ManageOverpaymentDifferenceService;
import com.ruicar.afs.cloud.manage.common.util.CreatCaseNoUtil;
import com.ruicar.afs.cloud.manage.common.vo.ContractCloseManageVO;
import com.ruicar.afs.cloud.manage.workflow.processor.ApproveTaskProcessor;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description:
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/contractClose")
public class ManageOverpaymentDifferenceController {

    private final ManageOverpaymentDifferenceService manageOverpaymentDifferenceService;
    private final ApproveTaskProcessor approveTaskProcessor;
    private final ManageApplyRecordService manageApplyRecordService;
    @ApiOperation(value = "未关闭的且已经做了结清的合同，如果撤销了合同最后一笔收款，则删除合同关闭表的数据")
    @PostMapping("/delete")
    public IResponse delete(@RequestParam("contractNo") String contractNo) {
        ManageOverpaymentDifference manageOverpaymentDifference = manageOverpaymentDifferenceService.getOne(Wrappers.<ManageOverpaymentDifference>lambdaQuery().eq(ManageOverpaymentDifference::getContractNo, contractNo));
        if (EmptyUtils.isNotEmpty(manageOverpaymentDifference) && EmptyUtils.isNotEmpty(manageOverpaymentDifference.getCloseDate())) {
            return new IResponse().fail("合同已关闭成功！");
        }

        boolean result = manageOverpaymentDifferenceService.remove(Wrappers.<ManageOverpaymentDifference>lambdaQuery().eq(ManageOverpaymentDifference::getContractNo, contractNo));
        if (result) {
            return new IResponse().success("删除成功");
        } else {
            return new IResponse().fail("删除失败");
        }
    }

    @ApiOperation(value = "查询合同关闭列表数据")
    @PostMapping("/findContractCloseList")
    public IResponse findContractCloseList(@RequestBody QueryCondition<ContractCloseManageVO> vo) {
        Page page = new Page(vo.getPageNumber(), vo.getPageSize());
        vo.getCondition().setProcessPerson(SecurityUtils.getUser().getUsername());
        IPage list = manageOverpaymentDifferenceService.getContractCloseList(page, vo.getCondition());
        list.setRecords(approveTaskProcessor.handle(list.getRecords()));
        return new IResponse().setData(list);
    }

    @ApiOperation(value = "合同结清后向合同关闭表插入数据")
    @PostMapping("/saveManageOverpaymentDifference")
    @Transactional(rollbackFor = Exception.class)
    public IResponse saveManageOverpaymentDifference(@RequestBody OverpaymentDifferenceDTO dto) {
        ManageOverpaymentDifference findOverpaymentDifference = manageOverpaymentDifferenceService.getOne(Wrappers.<ManageOverpaymentDifference>lambdaQuery().
                eq(ManageOverpaymentDifference::getContractNo, dto.getContractNo()));
        if (EmptyUtils.isNotEmpty(findOverpaymentDifference)) {
            return new IResponse().success("保存成功");
        }

        ManageOverpaymentDifference manageOverpaymentDifference = JSON.parseObject(JSON.toJSONString(dto), ManageOverpaymentDifference.class);
        boolean result = manageOverpaymentDifferenceService.save(manageOverpaymentDifference);
        if (result) {
            return new IResponse().success("保存成功");
        } else {
            return new IResponse().fail("保存失败");
        }
    }

    @ApiOperation(value = "查询合同关闭页面详细数据")
    @PostMapping("/findByIdDetails")
    public IResponse<OverpaymentDifferenceDTO> findByIdDetails(@RequestParam("contractNo") String contractNo) {
        ManageOverpaymentDifference manageOverpaymentDifference = manageOverpaymentDifferenceService.getOne(Wrappers.<ManageOverpaymentDifference>lambdaQuery().
                eq(ManageOverpaymentDifference::getContractNo, contractNo));
        OverpaymentDifferenceDTO overpaymentDifferenceDTO = JSON.parseObject(JSON.toJSONString(manageOverpaymentDifference), OverpaymentDifferenceDTO.class);
        return new IResponse<OverpaymentDifferenceDTO>().setData(overpaymentDifferenceDTO);
    }

    @ApiOperation(value = "更新合同关闭信息")
    @PostMapping("/submit")
    @Transactional(rollbackFor = Exception.class)
    public IResponse submit(@RequestBody ManageOverpaymentDifference difference) {
        if (EmptyUtils.isEmpty(difference.getCaseNo())) {
            // 生成案件编号
            difference.setCaseNo(CreatCaseNoUtil.GeneratorCaseNo(ContractBusinessEnum.overpayment));
        }
        manageOverpaymentDifferenceService.updateById(difference);
        return new IResponse().setData(difference);
    }

    @PostMapping("/submitOverpayment")
    @ApiOperation(value = "提交合同关闭业务信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse submitOverpayment(@RequestBody ContractCloseManageVO vo) {
        manageOverpaymentDifferenceService.submitOverpayment(vo);
        return new IResponse<Boolean>().setData(true).setMsg("流程提交成功！");
    }

    @PostMapping("/approveOverpayment")
    @ApiOperation(value = "流程审批操作")
    @Transactional(rollbackFor = Exception.class)
    public IResponse approveOverpayment(@RequestBody ContractCloseManageVO vo) {
        String string = manageOverpaymentDifferenceService.approveOverpayment(vo);
        if (EmptyUtils.isNotEmpty(string)) {
            return IResponse.fail(string);
        } else {
            return new IResponse<String>().setMsg("成功！");
        }
    }

    @ApiOperation(value = "关闭合同")
    @PostMapping("/closeContract")
    public IResponse closeContract(@RequestBody ManageOverpaymentDifference difference) {
        manageOverpaymentDifferenceService.closeContract(difference);
        return new IResponse().setData(difference);
    }

    @ApiOperation(value = "发起溢缴款校验")
    @PostMapping("/startOverflow")
    public IResponse startOverflow(@RequestBody ManageOverpaymentDifference difference) {
        List<ManageApplyRecord> collectCancel = manageApplyRecordService.list(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getContractNo, difference.getContractNo() )
                .eq(ManageApplyRecord::getContractBusiness, ContractBusinessEnum.collectionRevoke)
                .eq(ManageApplyRecord::getCaseStatus, CaseStatusEnum.UNDER_REVIEW));
        if (EmptyUtils.isNotEmpty(collectCancel)) {
            return IResponse.fail("收款撤销正在审批中,无法发起溢缴款！");
        }else {
            return new IResponse().setMsg("允许发起溢缴款");
        }

    }
}
